package vip.xiaonuo.tasks;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.core.util.DateUtils;
import vip.xiaonuo.facedoor.modular.devicehistory.entity.DeviceHistory;
import vip.xiaonuo.facedoor.modular.devicehistory.service.DeviceHistoryService;
import vip.xiaonuo.facedoor.modular.idcardhistory.entity.IdCardHistory;
import vip.xiaonuo.facedoor.modular.idcardhistory.service.IdCardHistoryService;
import vip.xiaonuo.facedoor.modular.visitorhistory.entity.VisitorHistory;
import vip.xiaonuo.facedoor.modular.visitorhistory.service.VisitorHistoryService;

import java.util.Date;


@Component
@Slf4j
public class CleanRecordTask implements TimerTaskRunner {

    @Autowired
    private IdCardHistoryService idCardHistoryService;

    @Autowired
    private DeviceHistoryService deviceHistoryService;

    @Autowired
    private VisitorHistoryService visitorHistoryService;

    @Override
    public void action(String taskId,String taskParam) {
        execute();
    }

    private void execute() {
        log.info("执行删除通行记录");
        Integer recordSaveDay = ConstantContextHolder.getSysConfig("RECORD_SAVE_DAY", Integer.class, true);
        Date date = DateUtils.addDay(new Date(), -recordSaveDay);
        idCardHistoryService.remove(new LambdaQueryWrapper<IdCardHistory>().le(IdCardHistory::getComparedDate,date));
        deviceHistoryService.remove(new LambdaQueryWrapper<DeviceHistory>().le(DeviceHistory::getDeviceCurrentDate,date));
        visitorHistoryService.remove(new LambdaQueryWrapper<VisitorHistory>().le(VisitorHistory::getDeviceCurrentDate,date));
    }

    @Override
    @XxlJob("CleanRecordTask")
    public void executeXxlJob() {
        this.execute();
    }
}
